package com.dl7.player.utils;

import ohos.aafwk.ability.Ability;
import ohos.accessibility.ability.AccessibleAbility;
import ohos.accessibility.ability.SoftKeyBoardController;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import java.lang.reflect.Method;

/**
 * SoftInputUtils
 *
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2014-5-07
 */
public class SoftInputUtils {

    private SoftInputUtils() {
        throw new AssertionError();
    }


    /**
     * 关闭键盘事件.
     *
     * @param context the context
     */
    public static void closeSoftInput(Context context) {
        SoftKeyBoardController softKeyBoardController = new SoftKeyBoardController(1, context);
        softKeyBoardController.setShowMode(AccessibleAbility.SHOW_MODE_HIDE);

//        InputMethodManager inputMethodManager = (InputMethodManager) context
//                .getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (inputMethodManager != null
//                && ((Ability) context).getCurrentFocus() != null) {
//            inputMethodManager.hideSoftInputFromWindow(((Ability) context)
//                            .getCurrentFocus().getWindowToken(),
//                    InputMethodManager.HIDE_NOT_ALWAYS);
//        }
    }

    /**
     * 弹出输入法
     *
     * @param context context
     * @param component    编辑控件
     */
    public static void setEditFocusable(final Context context, final Component component) {
        component.setTouchFocusable(true);
        component.requestFocus();
        WindowManager windowManager = WindowManager.getInstance();
        windowManager.addComponent((ComponentContainer) component
                , context, WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
    }

    public static boolean showSoftInput() {
        try {
            Class inputClass = Class.forName("ohos.miscservices.inputmethod.InputMethodController");
            Method method = inputClass.getMethod("getInstance");
            Object object = method.invoke(new Object[]{});
            Method startInput = inputClass.getMethod("startInput", int.class, boolean.class);
            return (boolean)startInput.invoke(object, 1, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean hideSoftInput() {
        try {
            Class inputClass = Class.forName("ohos.miscservices.inputmethod.InputMethodController");
            Method method = inputClass.getMethod("getInstance");
            Object object = method.invoke(new Object[]{});
            Method stopInput = inputClass.getMethod("stopInput", int.class);
            return (boolean)stopInput.invoke(object, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
